import React, { useState, useEffect } from 'react';
import { Checkbox, Button, Input, Modal } from 'antd';
import type { CheckboxChangeEvent } from 'antd/es/checkbox';
import { debounce } from 'lodash';
import { List, AutoSizer } from 'react-virtualized';
import { CloseOutlined, SearchOutlined } from '#/utils/antdIcons.js';
import TRNotification from '#/utils/notification.js';
import { iconPeople, iconPhone, iconEmail } from '@/assets/icon/index.js';
import type { ICreatorOption } from '../../type';
import styles from './index.less';

interface IProps {
  /**
   * 选择值
   */
  value?: number[];
  /**
   * 选择项
   */
  options: ICreatorOption[];

  onPress: (data: Record<string, any>) => void;

  dataObj: Record<string, ICreatorOption>;
}

const CreaterModalComponent = (props: IProps) => {
  const { value = [], onPress, dataObj, options = [] } = props;
  const [visible, setVisible] = useState<boolean>(true);
  const [checkedList, setCheckedList] = useState<number[]>(value);
  const [checkedData, setCheckedData] = useState<ICreatorOption[]>([]);
  const [showOptions, setShowOptions] = useState<ICreatorOption[]>([]);
  const [originOptions, setOriginOptions] = useState<ICreatorOption[]>(options);
  const [indeterminate, setIndeterminate] = useState(true);
  const [checkAll, setCheckAll] = useState(false);
  const [personSearch, setPersonSearch] = useState<string>();

  useEffect(() => {
    setIndeterminate(!!checkedList.length && checkedList.length < showOptions.length);
    if (!!checkedList.length && checkedList.length === showOptions.length) {
      setCheckAll(true);
    } else {
      setCheckAll(false);
    }
  }, [checkedList, showOptions]);

  // 获取选中人员的详情列表
  const getCheckedData = (list: number[]) => {
    if (!!list.length) {
      const data = list.map((item) => {
        const key = String(item);
        return dataObj[key];
      });
      return data;
    }
    return [];
  };

  // 根据传入的value值组装数据
  const getOriginOptions = (list: ICreatorOption[], arr: number[], checked: boolean) => {
    let _arr: any = [];
    if (arr.length > 0) {
      list.forEach((item: ICreatorOption) => {
        let obj = item;
        arr.forEach((i) => {
          if (item.value === i) {
            obj = { ...item, checked };
          }
        });
        _arr = [..._arr, obj];
      });
      return _arr;
    } else {
      return list;
    }
  };

  useEffect(() => {
    const data: ICreatorOption[] = getCheckedData(value);
    setCheckedData(data);
    const arr = getOriginOptions(options, value, true);
    setOriginOptions(arr);
    setShowOptions(arr);
  }, [value, options]);

  // 获取搜索数据
  const getSearchData = (keyWord: string, arr: ICreatorOption[]) => {
    const list: ICreatorOption[] = arr.filter((item: ICreatorOption) => {
      return (
        (item?.email && item?.email?.indexOf(keyWord) !== -1) ||
        (item?.mobile && item?.mobile?.indexOf(keyWord) !== -1) ||
        (item?.name && item?.name?.indexOf(keyWord) !== -1)
      );
    });
    return list;
  };

  // 选择
  const _onChange = (e: any) => {
    const _checked = e.target.checked;
    const _value = e.target.value;
    let list: ICreatorOption[] = [];
    const _originOptions = originOptions.map((item) => {
      if (item.value === _value) {
        return { ...item, checked: _checked };
      } else {
        return item;
      }
    });
    if (personSearch) {
      list = getSearchData(personSearch, _originOptions);
    } else {
      list = _originOptions;
    }
    const _checkedList: number[] =
      list.filter((item) => item?.checked)?.map((item) => item.value) || [];
    const _checkedData: ICreatorOption[] = _originOptions.filter((item) => item?.checked) || [];
    setShowOptions(list);
    setOriginOptions(_originOptions);
    setCheckedList(_checkedList);
    setCheckedData(_checkedData);
  };

  // 全选
  const _onCheckAllChange = (e: any) => {
    const _checked = e.target.checked;
    let _checkedList = showOptions.map((item: ICreatorOption) => item.value);
    let _originOptions: ICreatorOption[] = [];
    let list: ICreatorOption[] = [];
    if (_checked) {
      _originOptions = getOriginOptions(originOptions, _checkedList, true);
    } else {
      _originOptions = getOriginOptions(originOptions, _checkedList, false);
    }
    if (personSearch) {
      list = getSearchData(personSearch, _originOptions);
    } else {
      list = _originOptions;
    }
    const _checkedData: ICreatorOption[] = _originOptions.filter((item) => item?.checked) || [];
    _checkedList =
      list.filter((item) => item?.checked)?.map((item: ICreatorOption) => item.value) || [];
    setShowOptions(list);
    setOriginOptions(_originOptions);
    setCheckedList(_checkedList);
    setCheckedData(_checkedData);
  };

  // 确定按钮
  const _onOk = () => {
    const list = checkedData.map((item: ICreatorOption) => item.value);
    onPress({ index: 1, checkedList: list });
    setVisible(false);
  };

  // 取消按钮
  const _onCancel = () => {
    setVisible(false);
    onPress({ index: 0 });
  };

  // 清空
  const handelClearOut = () => {
    const _checkedList = checkedData.map((item: ICreatorOption) => item.value);
    const _originOptions = getOriginOptions(originOptions, _checkedList, false);
    let list: ICreatorOption[] = [];
    if (personSearch) {
      list = getSearchData(personSearch, _originOptions);
    } else {
      list = _originOptions;
    }
    setShowOptions(list);
    setOriginOptions(_originOptions);
    setCheckedList([]);
    setCheckedData([]);
  };

  // 删除已选数据
  const handleDeleteCheckedData = (data: ICreatorOption) => {
    _onChange({ target: { checked: false, value: data.value } });
  };

  // 搜索
  const _onSearch = debounce((e: CheckboxChangeEvent) => {
    const keyWord = e.target.value;
    const _showOptions = getSearchData(keyWord, originOptions);
    const _checkedList =
      _showOptions?.filter((item) => item.checked)?.map((item) => item.value) || [];
    setShowOptions(_showOptions);
    setCheckedList(_checkedList);
    setPersonSearch(keyWord);
  }, 300);

  const footerRender = () => [
    <Button key="dtest1" onClick={_onCancel}>
      取消
    </Button>,
    <Button key="dtest2" type="primary" onClick={_onOk}>
      提交
    </Button>,
  ];

  const leftItemRender = ({ key, index, style }: any) => {
    const item: ICreatorOption = showOptions[index];
    return (
      <div className={styles.item} key={key} style={style}>
        <Checkbox
          value={item.userId}
          checked={item.checked}
          className={styles.checkBox}
          onChange={_onChange}
        >
          {item.name}
        </Checkbox>
        <div className={styles.info}>
          <div className={styles.mobile}>
            <img src={iconPhone} className={styles.logo} />
            {item.mobile || '暂无'}
          </div>
          <div className={styles.email}>
            <img src={iconEmail} className={styles.logo} />
            {item.email || '暂无'}
          </div>
        </div>
      </div>
    );
  };

  const rightItemRender = ({ key, index, style }: any) => {
    const item: ICreatorOption = checkedData[index];
    return (
      <div className={styles.item} key={key} style={style}>
        <div className={styles.info}>
          <div className={styles.name}>
            {item.name}
            <CloseOutlined
              className={styles.close}
              onClick={() => {
                handleDeleteCheckedData(item);
              }}
            />
          </div>
          <div className={styles.mobile}>
            <img src={iconPhone} className={styles.logo} />
            {item.mobile || '暂无'}
          </div>
          <div className={styles.email}>
            <img src={iconEmail} className={styles.logo} />
            {item.email || '暂无'}
          </div>
        </div>
      </div>
    );
  };

  return (
    <Modal
      className={styles.modal}
      centered
      maskClosable={false}
      visible={visible}
      title={
        <div className={styles.titleDiv}>
          <img src={iconPeople} className={styles.titleLogo} />
          <span className={styles.title}> 创建人 </span>
        </div>
      }
      onCancel={_onCancel}
      footer={footerRender()}
    >
      <div className={styles.container}>
        <div className={styles.left}>
          <Input placeholder="搜索" suffix={<SearchOutlined />} allowClear onChange={_onSearch} />
          <div className={styles.content}>
            <Checkbox indeterminate={indeterminate} onChange={_onCheckAllChange} checked={checkAll}>
              全选
            </Checkbox>
            <AutoSizer>
              {({ height, width }: any) => (
                <div className={styles.checkboxGroup}>
                  <List
                    height={height}
                    width={width}
                    rowCount={showOptions?.length || 0}
                    rowHeight={80}
                    rowRenderer={leftItemRender}
                    key="userId"
                  />
                </div>
              )}
            </AutoSizer>
          </div>
        </div>
        <div className={styles.right}>
          <div className={styles.rightTop}>
            <div>已选{checkedData?.length || 0}项</div>
            <div onClick={handelClearOut} className={styles.clear}>
              清空
            </div>
          </div>
          <div className={styles.content}>
            <AutoSizer>
              {({ height, width }: any) => (
                <List
                  height={height}
                  rowCount={checkedData?.length || 0}
                  rowHeight={80}
                  rowRenderer={rightItemRender}
                  width={width}
                  key="userId"
                />
              )}
            </AutoSizer>
          </div>
        </div>
      </div>
    </Modal>
  );
};

class CreaterModal {
  __key__ = '';

  show = (props: any) => {
    return new Promise((resolve) => {
      if (this.__key__ !== '') return;
      this.__key__ = String(Date.now());
      TRNotification.add({
        key: this.__key__,
        content: (
          <CreaterModalComponent
            {...props}
            onPress={(result: any) => {
              TRNotification.remove(this.__key__);
              this.__key__ = '';
              resolve(result);
            }}
          />
        ),
        duration: null,
        dismiss: this.dismiss,
      });
    });
  };

  dismiss = () => {
    if (this.__key__.length > 0) {
      TRNotification.remove(this.__key__);
      this.__key__ = '';
    }
  };
}

export default new CreaterModal();
